import { GetCookie } from "./utils.js";

var modData = {};

async function ChangeUserConfig(access_token) {
  var pbody = `access_token=${encodeURIComponent(access_token)}`;
  for (const key in modData) {
    pbody += `&${encodeURIComponent(key)}=${encodeURIComponent(modData[key])}`;
  }
  const response = await fetch("http://localhost:9966/user/changeconfig", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: pbody,
  });

  if (!response.ok) {
    throw new Error("网络错误或未授权访问");
  }
  const data = await response.json();
  if (data.retcode !== 0) {
    throw new Error(`修改用户配置失败: ${data.retcode}`);
  }
  console.log("用户配置修改成功:", data);
  alert("用户配置修改成功");
  // window.location.href = "/pages/user_home.html"; // 修改成功后重定向到首页
}

async function GetUserData(access_token) {
  const response = await fetch(
    `http://localhost:9966/user/info?access_token=${encodeURIComponent(
      access_token
    )}`,
    {
      method: "GET",
    }
  );

  if (!response.ok) {
    throw new Error("网络错误或未授权访问");
  }
  const data = await response.json();
  if (data.retcode !== 0) {
    throw new Error(`获取用户数据失败: ${data.retcode}`);
  } else {
    OnGetUserData(data);
  }
}

function InitSignTimePickers(
  defaultBeginTime = "10:00",
  defaultEndTime = "19:00"
) {
  const startPickerElem = document.getElementById("startTimePicker");
  const endPickerElem = document.getElementById("endTimePicker");
  const startTimeInput = document.getElementById("start_time_input");
  const endTimeInput = document.getElementById("end_time_input");

  const startPicker = new tempusDominus.TempusDominus(startPickerElem, {
    defaultDate: new Date(`1970-01-01T${defaultBeginTime}:00`),
    display: {
      icons: {
        type: "icons",
        time: "bi bi-clock",
        date: "bi bi-calendar",
        up: "bi bi-chevron-up",
        down: "bi bi-chevron-down",
        previous: "bi bi-chevron-left",
        next: "bi bi-chevron-right",
        today: "bi bi-calendar-check",
        clear: "bi bi-trash",
        close: "bi bi-check2",
      },
      components: {
        calendar: false,
        date: false,
        month: false,
        year: false,
        decades: false,
        hours: true,
        minutes: true,
        seconds: false,
      },
      buttons: {
        close: true,
      },
    },
    localization: {
      locale: "zh-CN",
    },
  });

  const endPicker = new tempusDominus.TempusDominus(endPickerElem, {
    defaultDate: new Date(`1970-01-01T${defaultEndTime}:00`),
    display: {
      icons: {
        type: "icons",
        time: "bi bi-clock",
        date: "bi bi-calendar",
        up: "bi bi-chevron-up",
        down: "bi bi-chevron-down",
        previous: "bi bi-chevron-left",
        next: "bi bi-chevron-right",
        today: "bi bi-calendar-check",
        clear: "bi bi-trash",
        close: "bi bi-check2",
      },
      components: {
        calendar: false,
        date: false,
        month: false,
        year: false,
        decades: false,
        hours: true,
        minutes: true,
        seconds: false,
      },
      buttons: {
        close: true,
      },
    },
    localization: {
      locale: "zh-CN",
    },
  });

  startPicker.subscribe(tempusDominus.Namespace.events.change, (e) => {
    startTimeInput.value = e.date ? e.date.format("HH:mm") : "";
  });

  endPicker.subscribe(tempusDominus.Namespace.events.change, (e) => {
    endTimeInput.value = e.date ? e.date.format("HH:mm") : "";
  });

  const latestSignInTimeTxt = document.getElementById("latest_signin_time_txt");
  const earliestSignOutTimeTxt = document.getElementById(
    "earliest_signout_time_txt"
  );
  const timePicker = document.getElementById("time_picker");
  const timePickerModal = new bootstrap.Modal(timePicker);
  timePicker.addEventListener("shown.bs.modal", function () {
    startTimeInput.value = latestSignInTimeTxt.textContent;
    endTimeInput.value = earliestSignOutTimeTxt.textContent;
  });
  const confirmSignTimeBtn = document.getElementById("confirm_sign_time_btn");
  confirmSignTimeBtn.addEventListener("click", function () {
    const startTime = startTimeInput.value;
    const endTime = endTimeInput.value;
    console.log("确认签到时间:", startTime, "到", endTime);
    timePickerModal.hide();
    if (!startTime || !endTime) {
      alert("请填写完整的签到时间");
      return;
    } else if (startTime >= endTime) {
      alert("结束时间必须晚于开始时间");
      return;
    }
    latestSignInTimeTxt.textContent = startTime;
    earliestSignOutTimeTxt.textContent = endTime;
    modData.latest_signin_per_day =
      new Date(`1970-01-01T${startTime}:00`).getHours() * 3600 +
      new Date(`1970-01-01T${startTime}:00`).getMinutes() * 60;
    modData.earliest_signout_per_day =
      new Date(`1970-01-01T${endTime}:00`).getHours() * 3600 +
      new Date(`1970-01-01T${endTime}:00`).getMinutes() * 60;
  });

  const cancelSignTimeBtn = document.getElementById("cancel_sign_time_btn");
  cancelSignTimeBtn.addEventListener("click", function () {
    console.log("取消签到时间设置");
    timePickerModal.hide();
  });
}

function InitWorkTimePickers(
  min_work_time = 8,
  earliest_signin_time = "00:00",
  latest_signout_time = "23:59"
) {
  const minWorkTimeInput = document.getElementById("min_work_time_input");
  const earliestSigninTimeInput = document.getElementById(
    "earliest_signin_time_input"
  );
  const latestSignoutTimeInput = document.getElementById(
    "latest_signout_time_input"
  );

  const earliestSigninPickerElem = document.getElementById(
    "earliest_signin_time_picker"
  );
  const latestSignoutPickerElem = document.getElementById(
    "latest_signout_time_picker"
  );
  const earliestSigninPicker = new tempusDominus.TempusDominus(
    earliestSigninPickerElem,
    {
      defaultDate: new Date(`1970-01-01T${earliest_signin_time}:00`),
      display: {
        icons: {
          type: "icons",
          time: "bi bi-clock",
          date: "bi bi-calendar",
          up: "bi bi-chevron-up",
          down: "bi bi-chevron-down",
          previous: "bi bi-chevron-left",
          next: "bi bi-chevron-right",
          today: "bi bi-calendar-check",
          clear: "bi bi-trash",
          close: "bi bi-check2",
        },
        components: {
          calendar: false,
          date: false,
          month: false,
          year: false,
          decades: false,
          hours: true,
          minutes: true,
          seconds: false,
        },
        buttons: {
          close: true,
        },
      },
      localization: {
        locale: "zh-CN",
      },
    }
  );
  const latestSignoutPicker = new tempusDominus.TempusDominus(
    latestSignoutPickerElem,
    {
      defaultDate: new Date(`1970-01-01T${latest_signout_time}:00`),
      display: {
        icons: {
          type: "icons",
          time: "bi bi-clock",
          date: "bi bi-calendar",
          up: "bi bi-chevron-up",
          down: "bi bi-chevron-down",
          previous: "bi bi-chevron-left",
          next: "bi bi-chevron-right",
          today: "bi bi-calendar-check",
          clear: "bi bi-trash",
          close: "bi bi-check2",
        },
        components: {
          calendar: false,
          date: false,
          month: false,
          year: false,
          decades: false,
          hours: true,
          minutes: true,
          seconds: false,
        },
        buttons: {
          close: true,
        },
      },
      localization: {
        locale: "zh-CN",
      },
    }
  );
  earliestSigninPicker.subscribe(tempusDominus.Namespace.events.change, (e) => {
    earliestSigninTimeInput.value = e.date ? e.date.format("HH:mm") : "";
  });

  latestSignoutPicker.subscribe(tempusDominus.Namespace.events.change, (e) => {
    latestSignoutTimeInput.value = e.date ? e.date.format("HH:mm") : "";
  });

  minWorkTimeInput.value = min_work_time;
  earliestSigninTimeInput.value = earliest_signin_time;
  latestSignoutTimeInput.value = latest_signout_time;

  const workTimePanel = document.getElementById("work_time_panel");
  const workTimeModal = new bootstrap.Modal(workTimePanel);

  const confirmWorkTimeBtn = document.getElementById("confirm_work_time_btn");
  confirmWorkTimeBtn.addEventListener("click", function () {
    // 在这里添加保存工作时间的逻辑
    workTimeModal.hide();
    modData.min_work_time = parseFloat(minWorkTimeInput.value, 8);
    modData.earliest_signin_per_day =
      new Date(`1970-01-01T${earliestSigninTimeInput.value}:00`).getHours() *
        3600 +
      new Date(`1970-01-01T${earliestSigninTimeInput.value}:00`).getMinutes() *
        60;
    modData.latest_signout_per_day =
      new Date(`1970-01-01T${latestSignoutTimeInput.value}:00`).getHours() *
        3600 +
      new Date(`1970-01-01T${latestSignoutTimeInput.value}:00`).getMinutes() *
        60;
  });

  const cancelWorkTimeBtn = document.getElementById("cancel_work_time_btn");
  cancelWorkTimeBtn.addEventListener("click", function () {
    // 在这里可以添加取消操作的逻辑
    workTimeModal.hide();
  });
}

async function CompleteFunc() {
  try {
    await ChangeUserConfig(GetCookie("access_token"));
    await GetUserData(GetCookie("access_token"));
  } catch (error) {
    console.error("操作失败:", error);
  }
}

function OnGetUserData(data) {
  console.log("获取用户数据成功:", data);
  const userInfo = data.info;
  if (!userInfo) {
    console.error("用户信息未找到");
    return;
  }
  const signConfig = userInfo.sign_config;
  if (!signConfig) {
    console.error("签到配置未找到");
    return;
  }
  const accountNameElem = document.getElementById("account_name_text");
  accountNameElem.textContent = data.account ? data.account : "-";

  InitSignTimePickers(
    signConfig.latest_signin_time || "10:00",
    signConfig.earliest_signout_time || "19:00"
  );
  InitWorkTimePickers(
    signConfig.min_work_time || 8,
    signConfig.earliest_signin_time || "00:00",
    signConfig.latest_signout_time || "23:59"
  );
}

document.addEventListener("DOMContentLoaded", async function () {
  // 初始化设置按钮
  const access_token = GetCookie("access_token");
  if (!access_token) {
    alert("请先登录");
    window.location.href = "/index.html"; // 如果没有登录，重定向到登录页面
    return;
  }
  await GetUserData(access_token);
});

window.CompleteFunc = CompleteFunc;
